package com.jwgcs.runningDog.entity;

import com.jwgcs.runningDog.controller.RunningDogController;
import javafx.event.EventHandler;
import javafx.scene.AccessibleAttribute;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;

/**
 * Created by Administrator on 2015/10/27.
 */
public class EditingCell extends TableCell<Param,Integer>{

    private TextField textField;


    @Override
    public void startEdit() {
        int ci = (Integer)super.queryAccessibleAttribute(AccessibleAttribute.COLUMN_INDEX);
        int index = super.getIndex();
        super.startEdit();
        if (isEmpty()) {
            return;
        }
        if (textField == null) {
            createTextField();
        }
        textField.setText(String.valueOf(RunningDogController.PARAMS[index][ci-1]));
        setGraphic(textField);
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

    private void createTextField() {
        textField = new TextField(String.valueOf(getItem()));
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.ENTER) {
                    edit();
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }

            }
        });

        textField.setOnMouseExited(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                edit();
            }
        });
    }

    private void edit(){
        int ci = (Integer)super.queryAccessibleAttribute(AccessibleAttribute.COLUMN_INDEX);
        int index = super.getIndex();
        int v = Integer.valueOf(textField.getText());
        commitEdit(Integer.valueOf(textField.getText()));
        setItem(v);
        RunningDogController.PARAMS[index][ci-1] = v;
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    @Override
    public void updateItem(Integer item, boolean empty) {
        super.updateItem(item, empty);
        if (!isEmpty()) {
            if (textField != null) {
                textField.setText(String.valueOf(item));
            }
            setText(String.valueOf(item));
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

}
